import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import {getPathById, getObjById} from './utils';
import * as api from './api';
/*==============================初始化API================================= */
export const GET_INIT_BEGIN = 'GET_INIT_BEGIN';
export const GET_INIT_SUCCESS = 'GET_INIT_SUCCESS';
export const GET_INIT_FAIL = 'GET_INIT_FAIL';
export const getInitDataBegin = () => ({
    type: GET_INIT_BEGIN
});
export const getInitDataSuccess = data => ({
    type: GET_INIT_SUCCESS,
    data,
});
export const getInitDataFail = () => ({
    type: GET_INIT_FAIL,
});
export const getInitData = (code = PAGE_CODE) => dispatch => getCurrentUserPagePermissionsApi(code).then(res => {
    if(res.isOk) dispatch(getCurrentUserPagePermissionsSuccess(res.data));
    else dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
    return res.isOk;
});

export const GET_CATEGORY_BEGIN = 'GET_CATEGORY_BEGIN';
export const GET_CATEGORY_SUCCESS = 'GET_CATEGORY_SUCCESS';
export const GET_CATEGORY_FAIL = 'GET_CATEGORY_FAIL';
export const getCategoryBegin = () => ({
    type: GET_CATEGORY_BEGIN
});

export const getCategorySuccess = (data, parentId) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, parentId) || [];
    const newData = parentId ? data.map(item => {
        item.parentId = parentId;
        return item;
    }) : data;
    return dispatch({
        type: GET_CATEGORY_SUCCESS,
        data: newData,
        path
    });
};
export const getCategoryFail = () => ({
    type: GET_CATEGORY_FAIL,
});
export const getTopCategories = (forceRefresh = true) => (dispatch, getState) => {
    if(!forceRefresh) {
        const categories = getState().getIn(['page', 'domainData', 'categories', 'data']);
        if(categories && !categories.isEmpty())
            return Promise.resolve(true);
    }
    dispatch(getCategoryBegin());
    return api.getCategoriesTop().then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data || []));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    });
};

export const getCategoryChildren = parentId => dispatch =>
    // dispatch(getCategoryBegin());
    api.getCategories(parentId).then(res => {
        if(res.ok) {
            const {content = []} = res.data;
            const data = content.map(item => ({
                items: [],
                ...item
            }));
            dispatch(getCategorySuccess(data, parentId));
        } else
            dispatch(getCategoryFail());
        return res.ok;
    })
;
/*==============================查询列表================================= */

export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';
export const getListBegin = () => ({
    type: GET_LIST_BEGIN
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition
});
export const getListFail = () => ({
    type: GET_LIST_FAIL,
}); //获取列表

export const getList = condition => dispatch => {
    dispatch(getListBegin());
    return api.getList(condition).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
        return res.ok;
    });
}; //按钮搜索

export const querySearch = () => (dispatch, getState) => {
    const condition = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS();
    dispatch(getList(condition));
}; //分页排序搜索

export const tableSearch = page => (dispatch, getState) => {
    const query = getState()
        .getIn(['page', 'appState', 'queryBySort'])
        .toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};


export const categorySearch = id => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    condition.faultModeCategoryId = id;
    return dispatch(getList(condition));
};

/*==============================导出================================= */
export const exportData = () => (dispatch, getState) => {
    const {pageIndex, pageSize, ...props} = getState()
        .getIn(['page', 'appState', 'queryCondition'])
        .toJS() || {};
    return api.exportInfo(props);
};


//重置查询条件

export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL,
});
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
/*==============================新增维修项目分类================================ */

export const ADD_CATEGORY = 'ADD_CATEGORY';
export const onClickAddCategory = data => (dispatch, getState) => api.addCategory(data).then(res => {
    if(res.ok) {
        const {parentId, ...props} = data;
        const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
        const path = getPathById(trees, parentId) || [];
        dispatch({
            type: ADD_CATEGORY,
            path,
            data: {
                ...props,
                ...res.data,
                items: [],
                isNew: true
            }
        });
    }
    return res.ok;
});

/*==============================编辑维修项目分类================================ */
export const UPDATE_CATEGORY = 'UPDATE_CATEGORY';
export const updateCategory = (id, data) => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, id) || [];
    dispatch({
        type: UPDATE_CATEGORY,
        path,
        data
    });
};

export const onClickUpdateCategory = (data, id) => dispatch => {
    const {code, name, remark, rowVersion} = data;
    return api.updateCategory(id, {
        code,
        name,
        remark,
        rowVersion
    }).then(res => {
        if(res.ok)
            dispatch(updateCategory(id, {
                code,
                name,
                remark,
                ...res.data
            }));
        return res.ok;
    });
};

export const onSubmitCategory = (data, id) => dispatch => {
    if(id)
        return dispatch(onClickUpdateCategory(data, id));
    return dispatch(onClickAddCategory(data));
};
/*==============================停用维修项目分类================================ */
export const ABANDON_CATEGORY = 'ABANDON_CATEGORY';
export const abandonCategory = id => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const path = getPathById(trees, id) || [];
    dispatch({
        type: ABANDON_CATEGORY,
        path,
    });
};
export const onClickAbandonCategory = id => (dispatch, getState) => {
    const trees = getState().getIn(['page', 'domainData', 'categories', 'data']).toJS();
    const {rowVersion} = getObjById(trees, id) || {};
    return api.abandonCategory(id, {rowVersion}).then(res => {
        if(res.ok) {
            dispatch(abandonCategory(id));
            const {faultModeCategoryId} = getState()
                .getIn(['page', 'appState', 'queryCondition'])
                .toJS() || {};
            if(faultModeCategoryId && faultModeCategoryId === id)
                return dispatch(categorySearch());
        }
        return res.ok;
    });
};
/*==============================新增维修项目================================ */
/*==============================编辑维修项目================================ */
export const onClickUpdateInfo = data => (dispatch, getState) => {
    const {id, code, name, enName, esName, ptName, ruName, arName, faName, description, rowVersion} = data;
    const {faultModeCategoryId} = getState().getIn(['page', 'appState', 'queryBySort']).toJS() || {};
    if(id)
        return api.updateInfo(id, {
            name,
            enName,
            esName,
            ptName,
            ruName,
            arName,
            faName,
            description,
            rowVersion
        }).then(res => res.ok);
    return api.addInfo({
        faultModeCategoryId,
        code,
        name,
        enName,
        esName,
        ptName,
        ruName,
        arName,
        faName,
        description,
    }).then(res => res.ok);
};
/*==============================停用维修项目================================ */
export const onClickAbandonInfo = id => (dispatch, getState) => {
    const data = getState()
        .getIn(['page', 'domainData', 'list', 'data'])
        .toJS();
    const {rowVersion} = data.find(item => item.id === id);
    return api.abandonInfo(id, {
        rowVersion
    }).then(res => res.ok);
};
